package com.fast.user.service.member.impl;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

import javax.persistence.Query;

import org.apache.commons.beanutils.BeanUtils;
import org.jsoup.helper.DataUtil;
import org.springframework.stereotype.Service;

import com.fast.base.dao.daoSuport.JpaDaoSupport;
import com.fast.base.db.page.PageView;
import com.fast.base.db.page.QueryResult;
import com.fast.base.db.sql.AbstractSqlGenerator;
import com.fast.base.security.StringEncrypt;
import com.fast.base.util.LogUtils;
import com.fast.base.util.StringUtils;
import com.fast.base.util.ThreadPool;
import com.fast.base.util.data.DataRever;
import com.fast.base.util.data.MathUtils;
import com.fast.base.util.email.SendMail;
import com.fast.base.util.sms.MobileMsgUtils;
import com.fast.base.util.web.ResponseData;
import com.fast.cms.constant.CommonConstant;
import com.fast.common.excel.ExcelReader;
import com.fast.user.model.member.BrowseMemberInfo;
import com.fast.user.model.member.DeliveryAddress;
import com.fast.user.model.member.Member;
import com.fast.user.service.member.MemberService;
import com.fast.user.web.form.web.BrowerRecordsForm;
import com.fast.user.web.form.web.DeliveryAddressListForm;
import com.fast.user.web.form.web.MemberListForm;

/**
 * ClassName:MemberServiceImpl <br/>
 * 用途: Member服务接口的实现 <br/>
 * 开发人员：lushuifa  http://lushuifa.iteye.com/
 * 邮箱:lsflu@126.com
 * @version  
 * @since    JDK 1.6
 * @see
 * Date:     2016年11月30日 14时51分41秒; <br/>
 */
@Service("memberService")
public class MemberServiceImpl extends JpaDaoSupport  implements MemberService {
	

	@Override
	public boolean isExistUser(String loginName) {
		//先判断用户名
		long count = super.count(Member.class, " where loginName=?  and delete_flag=0 ",new Object[]{loginName});
		if(count>0){
			return true;
		}
		//判断手机
		count = super.count(Member.class, " where mobile=?  and delete_flag=0 ",new Object[]{loginName});
		if(count>0){
		    return true;
		}
		//判断邮箱
		count = super.count(Member.class, " where email=?  and delete_flag=0 ",new Object[]{loginName});
		if(count>0){
			return true;
		}
		return false;
	}

	/**
	 * 登录用户
	 */
	@Override
	public Member login(String loginName, String password) {
		//先查用户名
		Member member = null;
		member = super.query(Member.class, "where loginName='"+loginName+"' and loginPsd='"+StringEncrypt.SHA256(password)+"' and delete_flag=0");
		if(member!=null){
			return member;
		}
		//查手机号
		member = super.query(Member.class, "where mobile='"+loginName+"' and loginPsd='"+StringEncrypt.SHA256(password)+"' and delete_flag=0");
		if(member!=null){
			return member;
		}
		//查邮箱
		member = super.query(Member.class, "where email='"+loginName+"' and loginPsd='"+StringEncrypt.SHA256(password)+"' and delete_flag=0");
		if(member!=null){
			return member;
		}
	    return null;
	}
	
	/**
	 * 通过手机号来获取会员信息
	 * @param mobile 
	 * @return
	 */
	@Override
	public Member queryMemberByMobile(String mobile) {
		//查手机号
		return super.query(Member.class, "where mobile='"+mobile+"' and delete_flag=0");
	}
	

	@Override
	public int increaseLoginCount(int id) {
		//增加次数
		String sql = "update "+AbstractSqlGenerator.getTableName(Member.class)+" set loginCount=loginCount+1 where id="+id+"";
	    super.execute(sql);
		//返回最新次数
		String countSql = "select loginCount from "+AbstractSqlGenerator.getTableName(Member.class)+" where id="+id+"";
		return super.countBySql(countSql);
	}
	
	/**
	 * 说明:修改密码 <br>
	 * 编写者:lushuifa
	 * 创建时间:2016年10月23日 下午4:30:05 </pre>
	 * @param 
	 * @return ResponseData 说明
	 */
	public ResponseData updatePassword(int id,String newPassword){
		ResponseData responseData = new ResponseData();
		//先验证当前密码是否正确
		try {
			String updateSql = "update "+AbstractSqlGenerator.getTableName(Member.class)+" set loginPsd='"+StringEncrypt.SHA256(newPassword)+"' where id="+id;
			Query query = super.getEntityManager().createNativeQuery(updateSql);
			query.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}

	/**
	 * 发送短信验证码
	 */
	public String sendMobileCode(String mobile,String sendType) {
		int mobileCode = (int)((Math.random()*9+1)*100000);
		String msgContent = "";
		if(sendType.equals("findPsd")){
			 msgContent = "【默友科技】尊敬的用户您好，欢迎使用默友APP，您正在使用此号码找回用户密码，您的短信验证码为"+mobileCode+",如非本人操作，请与"+CommonConstant.WEBSITE_NAME+"客服联系!";
		}else{
			 msgContent = "【默友科技】尊敬的用户您好，欢迎使用默友APP，您的短信验证码为"+mobileCode+",如非本人操作，请与"+CommonConstant.WEBSITE_NAME+"客服联系!";
		}
		LogUtils.info("sendMobileCode msg:"+msgContent);
		Boolean sendFlag = MobileMsgUtils.sendSMS(mobile, msgContent);
        String reback = "";
		try {
			if(sendFlag){
				reback = mobileCode+"";
			}
		} catch (Exception e) {
			reback = "";
		}
        // 关闭线程池
		System.out.println("发送后");
		return reback;
	}

	/**
	 * 发送验证邮箱
	 */
	@Override
	public boolean sendRegCheckEmail(Member member,String basePath) {
		String emailContent = SendMail.getMailContent(basePath+"front/emailTlp/regist_email_tlp.html");
		String checkEmailRegUrl = basePath+"MemberController/checkEmailReg.do?uuid="+member.getUuid()+"&email="+member.getEmail();
		emailContent = emailContent.replace("../", basePath+"front/");
		emailContent = emailContent.replace("[loginName]",member.getNickName());
		emailContent = emailContent.replace("[checkEmailRegUrl]", checkEmailRegUrl);
		SendMail smail = new SendMail(""+CommonConstant.WEBSITE_NAME+"注册验证",member.getEmail(), emailContent);
		//拿到线程池
        ExecutorService pool = ThreadPool.getPool();
		Future<?> future = pool.submit(smail);
        boolean sendFlag = false;
		try {
			sendFlag = Boolean.valueOf(future.get().toString());
		} catch (Exception e) {
			sendFlag = false;
		}
        // 关闭线程池
        pool.shutdown();
        return sendFlag;
	}
    
	/**
	 * 作用：验证手机是否存在
	 * @see com.fast.user.service.member.MemberService#existMobile(java.lang.String)
	 */
	@Override
	public boolean existMobile(String mobile) {
		return super.isExist(Member.class, " where mobile='"+mobile+"' and delete_flag=0 ");
	}
	
	/**
	 * 作用：查看邮箱是否存在<br/>
	 * @author 卢水发
	 * @param email
	 * @return
	 * @since JDK 1.6
	 * boolean
	 */
	public boolean existEmail(String email){
		return super.isExist(Member.class, " where email='"+email+"' and delete_flag=0");
	}

	/**
	 * 作用：发送邮件<br/>
	 * @author 卢水发
	 * @param email
	 * @return
	 * @since JDK 1.6
	 * boolean
	 */
	public String sendEmailCode(String email, String sendType){
		int mailCode = (int)((Math.random()*9+1)*100000);
		String emailContent = "尊敬的用户您好，你正在使用此邮箱账号找回用户密码，你的验证码为["+mailCode+"],如非本人操作，请与"+CommonConstant.WEBSITE_NAME+"客服联系!";
		SendMail smail = new SendMail(""+CommonConstant.WEBSITE_NAME+"找回密码验证码",email,emailContent);
		//拿到线程池
        ExecutorService pool = ThreadPool.getPool();
		Future<?> future = pool.submit(smail);
        boolean sendFlag = false;
		try {
			sendFlag = Boolean.valueOf(future.get().toString());
		} catch (Exception e) {
			sendFlag = false;
		}
        // 关闭线程池
        pool.shutdown();
        return mailCode+"";
	}

	/**
	 * 校验身份证是否存在
	 */
	@Override
	public boolean isExistIdCard(String idcard) {
		return super.isExist(Member.class," where idcard='"+idcard+"'  and delete_flag=0 ");
	}

	/**
	 * 核对密码是否存在
	 */
	@Override
	public boolean checkPassword(String uuid, String password) {
		return super.isExist(Member.class, " where uuid='"+uuid+"' and password='"+password+"'  delete_flag=0 ");
	}

	/**
	 * 是否存在某个用户名
	 */
	@Override
	public boolean isExistLoginName(String loginName) {
		return super.isExist(Member.class, " where loginName='"+loginName+"'  and delete_flag=0");
	}
	
	/**
	 * 是否存在某个用户名
	 */
	@Override
	public boolean isExistLoginName(String loginName,int memberId) {
		return super.isExist(Member.class, " where loginName='"+loginName+"'  and delete_flag=0 and id!="+memberId);
	}
	
	/**
	 * 是否存在某个邮箱
	 */
	@Override
	public boolean isExistEmail(String email) {
		return super.isExist(Member.class, " where email='"+email+"'  and delete_flag=0");
	}
	
	/**
	 * 是否存在某个邮箱
	 */
	@Override
	public boolean isExistEmail(String email,int memberId) {
		return super.isExist(Member.class, " where email='"+email+"'  and delete_flag=0 and id!="+memberId);
	}
	
	/**
	 * 是否存在某个手机号
	 */
	@Override
	public boolean isExistMobile(String mobile) {
		return super.isExist(Member.class, " where mobile='"+mobile+"'  and delete_flag=0");
	}
	
	/**
	 * 是否存在某个手机号
	 */
	@Override
	public boolean isExistMobile(String mobile,int memberId) {
		return super.isExist(Member.class, " where mobile='"+mobile+"'  and delete_flag=0 and id!="+memberId);
	}
	
	/**
	 * 通过ID
	 * @param id
	 * @return
	 */
	public Member getMemberById(int id){
		return super.getById(Member.class, id);
	}

	/**
	 * 查询会员列表
	 */
	@Override
	public PageView<Member> getMemberListByPage(MemberListForm memberListForm) {
		int page = memberListForm.getPage();//当前页
  		int pagesize = memberListForm.getRows();//每页面显示多少条
  		String memberType = memberListForm.getMemberType();
  		String loginName = memberListForm.getLoginName();
  		String mobile = memberListForm.getMobile();
  		String email = memberListForm.getEmail();
  		String realName = memberListForm.getRealName();
  		String deleteFlag = memberListForm.getDeleteFlag();
  		String locked = memberListForm.getLocked();
		StringBuffer sb = new StringBuffer(" where 1=1 ");
		if(StringUtils.isNotEmpty(email)){
			sb.append(" and email like '%"+email+"%' ");
		}
		if(StringUtils.isNotEmpty(mobile)){
			sb.append(" and mobile like '%"+mobile+"%' ");
		}
		if(StringUtils.isNotEmpty(loginName)){
			sb.append(" and loginName like '%"+loginName+"%' ");
		}
		if(StringUtils.isNotEmpty(realName)){
			sb.append(" and realName like '%"+realName+"%' ");
		}
		if(StringUtils.isNotEmpty(memberType)){
			sb.append(" and memberType="+memberType+" ");
		}
		if(StringUtils.isNotEmpty(locked)){
			sb.append(" and locked="+locked+" ");
		}
		if(StringUtils.isNotEmpty(deleteFlag)){
			sb.append(" and delete_flag="+deleteFlag+" ");
		}else{
			sb.append(" and delete_flag=0 ");
		}
		String ordersql = " order by edit_time desc ";
		QueryResult<Member>  queryResult = super.queryForBeanListByPage(Member.class, sb.toString(), ordersql,(page-1)*pagesize,pagesize);
		PageView<Member> pageView = new PageView<Member>();
	    pageView.setCurrentPage(page);
		pageView.setQueryResult(queryResult);
		return pageView;
	}
	
	/**
	 * 获取浏览记录（谁看过我）（我看过谁）
	 * @param browerRecordsForm
	 * @return
	 */
	public PageView<BrowseMemberInfo> getBrowerRecords(BrowerRecordsForm browerRecordsForm){
		int page = browerRecordsForm.getPage();//当前页
  		int pagesize = browerRecordsForm.getRows();//每页面显示多少条
		String ordersql = " order by edit_time desc ";
		QueryResult<BrowseMemberInfo>  queryResult = super.queryForBeanListByPage(BrowseMemberInfo.class, "", ordersql,(page-1)*pagesize,pagesize);
		PageView<BrowseMemberInfo> pageView = new PageView<BrowseMemberInfo>();
	    pageView.setCurrentPage(page);
		pageView.setQueryResult(queryResult);
		return pageView;
	}
	
	/**
	 * 获取邮寄地址列表
	 * @param deliveryAddressListForm
	 * @return
	 */
	public PageView<DeliveryAddress> queryDeliveryAddressList(DeliveryAddressListForm deliveryAddressListForm){
		int page = deliveryAddressListForm.getPage();//当前页
  		int pagesize = deliveryAddressListForm.getRows();//每页面显示多少条
		String ordersql = " order by edit_time desc ";
		QueryResult<DeliveryAddress>  queryResult = super.queryForBeanListByPage(DeliveryAddress.class, "", ordersql,(page-1)*pagesize,pagesize);
		PageView<DeliveryAddress> pageView = new PageView<DeliveryAddress>();
	    pageView.setCurrentPage(page);
		pageView.setQueryResult(queryResult);
		return pageView;
	}
	
	/**
	 * 说明: 获取会员信息<br>
	 * 编写者:lushuifa
	 * 创建时间:2018年4月22日 下午11:43:57 </pre>
	 * @param 
	 * @return Member 说明
	 */
	@Override
	public Member getMemberByUUID(String uuid) {
		return super.queryForBeanByUUID(Member.class, uuid);
	}
	
	/**
	 * 说明: 批量保存会员数据，从xls中读取数据写入<br>
	 * 编写者:lushuifa
	 * 创建时间:2018年8月18日 下午3:59:21 </pre>
	 * @param 
	 * @return boolean 说明
	 */
	public boolean batchSaveMemberByImpFile(String fileDiskPath) {
		//数据列：昵称`手机号`邮箱`真实姓名`性别`生日`身高（CM）`体重（KG）`国家`省份`备用地址`兴趣爱好
		try {
			ExcelReader excelReader = new ExcelReader();
			InputStream is2 = new FileInputStream(fileDiskPath);
			Map<Integer, String> map = excelReader.readExcelContent(is2);
			LogUtils.info("\n获得Excel表格的内容:");
			Member member = null;
			for (int i = 1; i <= map.size(); i++) {
				String str = map.get(i) + "0";
				if (!map.get(i).replace("`", "").trim().equals("")) {
					member = new Member();
					String[] props = str.split("`");
					member.setUuid(MathUtils.getTheOnlyStr());
					member.setNickName(props[0]);
					member.setMobile(props[1]);
					member.setEmail(props[2]);
					member.setRealName(props[3]);
					//1代表男,0代表女
					if(props[4].contains("男")) {
						member.setSex(1);
					}else if(props[4].contains("女")) {
						member.setSex(0);
					}else {
						member.setSex(2);
					}
					member.setBirthday(props[5]);
					member.setHeight(DataRever.getInt(props[6]));
					member.setWeight(DataRever.getInt(props[7]));
					member.setNationality(props[8]);
					member.setProvince(props[9]);
					member.setAreaPoint_b(props[10]);
					member.setInterest(props[11]);
					super.saveOrModify(member, " where mobile='"+member.getMobile()+"'");
				}
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}
